<template>
  <div class="app-container">
    <div class="filter-container">
      <!-- 上方搜索框模块 -->
      <div class="input-btn">
        <!-- 部门 -->
        <div class="fun-btn">
          <span>部门：</span>
          <el-input
            placeholder="点击选择"
            style="width: 200px;"
            class="filter-item"
            v-model="department"
          />
        </div>
        <!-- 等级 -->
        <div class="fun-btn">
          <span>等级：</span>
          <el-select
            v-model="gradeValue"
            placeholder="全部"
            clearable
            class="filter-item"
            style="width: 200px"
          >
            <el-option
              v-for="item in calendarTypeOptions"
              :key="item.key"
              :label="item.display_name+'('+item.key+')'"
              :value="item.key"
            />
          </el-select>
        </div>
        <!-- 状态 -->
        <div class="fun-btn">
          <span>状态：</span>
          <el-select
            placeholder="全部"
            clearable
            class="filter-item"
            style="width: 200px"
            v-model="staticValue"
          >
            <el-option
              v-for="item in stateOptions"
              :key="item.key"
              :label="item.display_name+'('+item.key+')'"
              :value="item.key"
            />
          </el-select>
        </div>
        <!-- 是否激活 -->
        <div class="fun-btn">
          <span>是否激活：</span>
          <el-select
            placeholder="全部"
            clearable
            class="filter-item"
            style="width: 200px"
            v-model="activeValue"
          >
            <el-option
              v-for="item in activationOptions"
              :key="item.key"
              :label="item.display_name+'('+item.key+')'"
              :value="item.key"
            />
          </el-select>
        </div>
        <!-- 搜索 -->
        <div class="fun-btn">
          <span>搜索：</span>
          <el-input
            placeholder="输入关键字"
            style="width: 200px;"
            class="filter-item"
            v-model="listQuery.title"
          />
          <el-button v-waves type="primary" icon="el-icon-search" class="search-bth">搜索</el-button>
        </div>
      </div>

      <!-- 新增和激活状态模块 -->
      <div class="add-btn">
        <el-button icon="el-icon-minus" class="minus">批量去激活</el-button>
        <el-button icon="el-icon-plus" class="minus">批量激活</el-button>
        <el-button icon="el-icon-plus" class="minus" @click="handleCreate">添加风险点</el-button>
      </div>

      <!-- 表格部分 -->
      <el-table
        :key="tableKey"
        :data="list"
        border
        fit
        highlight-current-row
        style="width: 100%;"
        @sort-change="sortChange"
      >
        <!-- 批量操作选框 -->
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <!-- 排序列 -->
        <el-table-column type="index" label="Id" align="center" width="60">
          <template slot-scope="{row}">
            <span>{{ row.id }}</span>
          </template>
        </el-table-column>
        <el-table-column label="风险点名称" width="180px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.title}}</span>
          </template>
        </el-table-column>
        <el-table-column label="风险点地点" width="120px" align="center">
          <template slot-scope="{row}">
            <span class="link-type" @click="handleUpdate(row)">{{ row.place }}</span>
          </template>
        </el-table-column>
        <el-table-column label="是否为重大风险源" width="150px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.danger }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center">
          <template slot-scope="{row}">
            <span>{{ row.remarks }}</span>
          </template>
        </el-table-column>
        <!-- 操作列 -->
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="{row,$index}">
            <el-button type="primary" size="mini" @click="handlepush($index)">检查项目</el-button>
            <el-button type="primary" size="mini" @click="handleUpdate(row)">编辑</el-button>
            <el-button size="mini" type="danger">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage4"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="2"
        layout="total, sizes, prev, pager, next, jumper"
        :total="2"
      ></el-pagination>

      <!-- 弹框 -->
      <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
        <el-form
          ref="dataForm"
          :model="temp"
          label-position="left"
          label-width="130px"
          style="width: 400px; margin-left:50px;"
        >
          <el-form-item label="风险点添加">
            <el-input v-model="temp.title"/>
          </el-form-item>
          <el-form-item label="是否重大危险源">
            <el-radio v-model="temp.danger" label="是">是</el-radio>
            <el-radio v-model="temp.danger" label="否">否</el-radio>
          </el-form-item>
          <el-form-item label="风险点场所">
            <el-input v-model="temp.place"/>
          </el-form-item>
          <el-form-item label="风险点描述">
            <el-input
              v-model="temp.remarks"
              :autosize="{ minRows: 2, maxRows: 4}"
              type="textarea"
              placeholder="Please input"
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">提交</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import Pagination from "@/components/Pagination";
import {
  fetchList,
  fetchPv,
  createArticle,
  updateArticle
} from "@/api/article";
import waves from "@/directive/waves";
import { parseTime } from "@/utils";

const calendarTypeOptions = [
  { key: "CN", display_name: "China" },
  { key: "US", display_name: "USA" },
  { key: "JP", display_name: "Japan" },
  { key: "EU", display_name: "Eurozone" }
];
const stateOptions = [
  { key: "CN", display_name: "1" },
  { key: "US", display_name: "2" },
  { key: "JP", display_name: "3" },
  { key: "EU", display_name: "4" }
];
const activationOptions = [
  { key: "CN", display_name: "001" },
  { key: "US", display_name: "002" },
  { key: "JP", display_name: "003" },
  { key: "EU", display_name: "004" }
];

export default {
  name: "ComplexTable",
  components: { Pagination },
  directives: { waves },

  data() {
    return {
      // 等级的数据
      calendarTypeOptions,
      // 状态的数据
      stateOptions,
      //是否激活的数据
      activationOptions,
      // 等级下拉选择框显示的内容
      gradeValue: "",
      //状态下拉选择框显示的内容
      staticValue: "",
      // 激活下拉选择框显示的内容
      activeValue: "",

      tableKey: 0,
      // list: null,
      list: [
        {
          id: "1",
          title: "王小虎",
          place: "上海",
          remarks: "备注内容",
          danger: "是"
        },
        {
          id: "2",
          title: "王大虎",
          place: "北京",
          remarks: "备注内容2",
          danger: "是"
        }
      ],
      // 分页里：要去第几页显示的页数
      currentPage4: 3,
      // 数据总条数
      total: 0,
      // 加载状态
      listLoading: true,
      // 搜索和分页要传的属性
      listQuery: {
        // 当前页数
        page: 1,
        // 每页的数量
        limit: 5,
        // importance: undefined,
        // 搜索的关键字
        title: undefined,
        type: undefined,
        sort: "+id"
      },
      // 部门写入的数据
      department: "",
      // 弹框中设置的数据
      temp: {
        id: undefined,
        // importance: 1,
        remarks: "",
        title: "",
        type: "",
        danger: "",
        place: ""
      },
      // 弹出框弹出状态
      dialogFormVisible: false,
      // 弹出框标题内容
      dialogStatus: "",
      textMap: {
        update: "Edit",
        create: "Create"
      }
    };
  },
  created() {
    // this.getList();
  },
  methods: {
    getList() {
      this.listLoading = true;
      fetchList(this.listQuery).then(response => {
        this.list = response.data.items;
        this.total = response.data.total;

        setTimeout(() => {
          this.listLoading = false;
        }, 1 * 1000);
      });
    },
    handlepush(index) {
      // this.$router.push("/riskMenu/riskpoint/inspection");
      this.$router.push({
        path: "/riskMenu/riskpoint/inspection",
        query: {
          id: index
        }
      });
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    sortChange(data) {
      console.log(data);
      const { prop, order } = data;
      if (prop === "id") {
        this.sortByID(order);
      }
    },
    sortByID(order) {
      if (order === "ascending") {
        this.listQuery.sort = "+id";
      } else {
        this.listQuery.sort = "-id";
      }
      this.handleFilter();
    },
    // 清空新增输入框里的内容
    resetTemp() {
      this.temp = {
        id: undefined,
        importance: 1,
        remarks: "",
        title: "",
        type: "",
        danger: "",
        place: ""
      };
    },
    handleCreate() {
      this.resetTemp();
      // 弹出框的标题改变
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    // 增
    createData() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.temp.id = parseInt(Math.random() * 100) + 1024; // mock a id
          this.temp.author = "vue-element-admin";
          createArticle(this.temp).then(() => {
            this.list.unshift(this.temp);
            this.dialogFormVisible = false;
            this.$notify({
              title: "Success",
              message: "Created Successfully",
              type: "success",
              duration: 2000
            });
          });
        }
      });
    },
    handleUpdate(row) {
      // 复制数据进去编辑框
      this.temp = Object.assign({}, row);
      // this.temp.timestamp = new Date(this.temp.timestamp);
      // 弹出框的标题改变
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    // 改
    updateData() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.temp);
          // tempData.timestamp = +new Date(tempData.timestamp);
          updateArticle(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id);
            this.list.splice(index, 1, this.temp);
            this.dialogFormVisible = false;
            this.$notify({
              title: "Success",
              message: "Update Successfully",
              type: "success",
              duration: 2000
            });
          });
        }
      });
    },
    // 删
    handleDelete(row, index) {
      this.$notify({
        title: "Success",
        message: "Delete Successfully",
        type: "success",
        duration: 2000
      });
      this.list.splice(index, 1);
    }
  }
};
</script>

<style lang="scss" scoped>
.el-table {
  margin-top: 16px;
}
.cancel {
  margin-top: 30px;
}
.fun-btn {
  float: left;
  margin-right: 24px;
  font-size: 14px;
  margin-bottom: 14px;
}
.search-bth {
  background: #009688;
  width: 65px;
  font-size: 14px;
  text-indent: -7px;
  margin-left: 24px;
}
.input-btn {
  height: 100px;
}
.add-btn {
  margin-top: 8px;
  height: 30px;
  display: flex;
}
.minus {
  background: #1e9fff;
  border: none;
  width: 85px;
  height: 30px;
  font-size: 12px;
  /* text-indent: -9px; */
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}
/* .el-form{
  width: 800px;
} */
</style>


